package com.cloudservice.ccs.controller;


import com.cloudservice.ccs.biz.ITagsBiz;
import com.cloudservice.ccs.model.ApiResult;
import com.cloudservice.ccs.model.PageData;
import com.cloudservice.ccs.entity.Tags;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/tags")
public class TagsController {
	@Autowired
	private ITagsBiz tagsBiz;

	@PostMapping("/")
	public ApiResult save(@RequestBody Tags tags) {
		// 接口问题待讨论：是否应当返回生成的 id？
		tagsBiz.save(tags);
		return ApiResult.success();
	}

	@PutMapping("/{id}")
	public ApiResult update(@PathVariable Integer id, @RequestBody Tags tags) {
		tagsBiz.update(id, tags);
		Tags result = tagsBiz.getOne(id);
		return ApiResult.successWithData(result);
	}

	// @RequiresPermissions("all")
	@PutMapping("/{id}/partial")
	public ApiResult partialUpdate(@PathVariable Integer id, @RequestBody Map<String, Object> fields) {
		tagsBiz.partialUpdate(id, fields);
		Tags result = tagsBiz.getOne(id);
		return ApiResult.successWithData(result);
	}

	@DeleteMapping("/{id}")
	public ApiResult delete(@PathVariable Integer id) {
		tagsBiz.delete(id);
		return ApiResult.success();
	}

	@DeleteMapping("/{ids}/deletePartial")
	public ApiResult batchDelete(@PathVariable String ids) {
		Arrays.asList(ids.split(",")).forEach(idString -> {
			Integer id = Integer.parseInt(idString);
			tagsBiz.delete(id);
		});
		return ApiResult.success();
	}

	@GetMapping("/{id}")
	public ApiResult queryById(@PathVariable Integer id) {
		Tags result = tagsBiz.getOne(id);
		return ApiResult.successWithData(result);
	}

	@RequiresPermissions("all")
	@GetMapping("/")
	public ApiResult queryAll(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "0") Integer limit) {
		PageHelper.startPage(page, limit);
		List<Tags> result = tagsBiz.getAll();
		return ApiResult.successWithData(PageData.fromPage((Page<Tags>) result));
	}
}
